#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>

void MainWindow::initStatusLeds()
{
    // 设置从板卡IP (示例IP，根据实际修改)
    QString slaveIps[4] = {"192.168.0.101", "192.168.0.102",
                           "192.168.0.103", "192.168.0.104"};
    // 清空原有布局
    QLayout* oldLayout = ui->groupBox_11->layout();
    if(oldLayout) {
        delete oldLayout;
    }

    // 创建水平布局
    QHBoxLayout* hLayout = new QHBoxLayout(ui->groupBox_11);
    hLayout->setSpacing(15);  // 设置控件间距
    hLayout->setContentsMargins(10, 5, 10, 5);  // 设置边距

    // 主板卡电源指示灯
    QWidget* masterWidget = new QWidget();
    QVBoxLayout* masterLayout = new QVBoxLayout(masterWidget);
    masterLayout->setContentsMargins(0, 0, 0, 0);
    masterLayout->setSpacing(3);

    // 主板卡电源指示灯 - 初始红色
    statusLeds.masterPower = new QLabel();
    statusLeds.masterPower->setFixedSize(30, 30);
    statusLeds.masterPower->setStyleSheet("background-color: red; border-radius: 10px;");

    QLabel* masterLabel = new QLabel("相机主控");
    masterLabel->setAlignment(Qt::AlignCenter);

    masterLayout->addWidget(statusLeds.masterPower, 0, Qt::AlignHCenter);
    masterLayout->addWidget(masterLabel);
    hLayout->addWidget(masterWidget);

    // 4个从板卡指示灯
    for (int i = 0; i < 4; i++) {
        QWidget* slaveWidget = new QWidget();
        QVBoxLayout* slaveLayout = new QVBoxLayout(slaveWidget);
        slaveLayout->setContentsMargins(0, 0, 0, 0);
        slaveLayout->setSpacing(3);

        statusLeds.slave[i].led = new QLabel();
        statusLeds.slave[i].led->setFixedSize(24, 24);
        statusLeds.slave[i].led->setStyleSheet("background-color: red; border-radius: 12px;");

        QLabel* slaveLabel = new QLabel(QString("CCD%1").arg(i));
        slaveLabel->setAlignment(Qt::AlignCenter);

        slaveLayout->addWidget(statusLeds.slave[i].led, 0, Qt::AlignHCenter);
        slaveLayout->addWidget(slaveLabel);
        hLayout->addWidget(slaveWidget);
    }

    // 添加伸缩因子使布局居中
    hLayout->insertStretch(0, 1);
    hLayout->addStretch(1);

    // 添加超时检测定时器 (每秒检测一次)
    QTimer* timeoutTimer = new QTimer(this);
    connect(timeoutTimer, &QTimer::timeout, this, &MainWindow::checkSlaveTimeout);
    timeoutTimer->start(1000);
}


void MainWindow::updateMasterLedStatus(bool isConnected)
{
    QString style;

    if (!isConnected) {
        // 未连接状态 - 红色
        style = "background-color: yellow; border-radius: 10px;";
    }
    else {
        // 根据相机状态设置颜色
        switch(cameraState.status) {
        case 0:  // 空闲
            style = "background-color: green; border-radius: 10px;";
            break;
        case 1:  // 曝光中
            style = "background-color: blue; border-radius: 10px;";
            break;
        case 2:  // 读出中
            style = "background-color: cyan; border-radius: 10px;";
            break;
        case -1:
            style = "background-color: red; border-radius: 10px;";
            break;
        default:
            style = "background-color: yellow; border-radius: 10px;";
        }
    }

    statusLeds.masterPower->setStyleSheet(style);
}

void MainWindow::updateCameraControls(bool isExposing) {
    // 曝光按钮
    ui->btnStartExposure->setEnabled(!isExposing);

    // 读出速度控制
    ui->comboBoxReadoutRate->setEnabled(!isExposing);

    // 快门控制按钮组
    ui->btnShutterOn->setEnabled(!isExposing);
    ui->btnShutterOff->setEnabled(!isExposing);
}

// Similar for other settings...
// 更新心跳状态显示
void MainWindow::updateHeartbeatStatus() {
    QString status;
    QColor color;

    if (m_isRegistered) {
        int elapsed = m_lastHeartbeatTime.secsTo(QDateTime::currentDateTime());
        status = QString("已连接 (%1秒前)").arg(elapsed);
        color = elapsed < 10 ? Qt::green : Qt::yellow;
    } else {
        status = "未连接";
        color = Qt::red;
    }

    ui->labelHeartbeatStatus->setText(status);
    ui->labelHeartbeatStatus->setStyleSheet(QString("color: %1").arg(color.name()));
}


void MainWindow::updateExposureProgress() {
    if (progressStartTime == 0) return;

    qint64 elapsed = QDateTime::currentMSecsSinceEpoch() - progressStartTime;
    int elapsedSecs = elapsed / 1000;
    int progress = 0;
    QString status;

    // 根据当前阶段计算进度
    if (currentPhase == PHASE_EXPOSING) {
        // 曝光阶段 (0-50%)
        int currentExposureTimeInt = currentExposureTime;
        progress = qMin(50, static_cast<int>(elapsedSecs * 50 / (currentExposureTimeInt+0.1)));
        status = QString("EXPOSING %1/%2 Seconds").arg(elapsedSecs).arg(currentExposureTimeInt);

        // 检查是否应该转入读出阶段
        if (elapsedSecs >= (currentExposureTimeInt+0.1)) {
            currentPhase = PHASE_READOUT;
            progressStartTime = QDateTime::currentMSecsSinceEpoch(); // 重置计时
            //LOG_GENERAL("进入读出阶段");
        }
    }
    else if (currentPhase == PHASE_READOUT) {
        // 读出阶段 (50-100%)
        int readoutElapsed = elapsedSecs;
        progress = 50 + qMin(50, readoutElapsed * 50 / 10); // 固定10秒读出
        status = QString("READOUT %1/10 Seconds").arg(readoutElapsed);

        // 检查是否完成
        if (readoutElapsed >= 10) {
            currentPhase = PHASE_IDLE;
            progressTimer->stop();
            progress = 100;
            status = "完成";
            //LOG_GENERAL("曝光流程完成");
        }
    }

    // 更新UI
    ui->ExposureprogressBar->setValue(progress);
    ui->labelProgressStatus->setText(status);

    // 可视化区分阶段
    QString style;
    if (currentPhase == PHASE_EXPOSING) {
        style = "QProgressBar::chunk { background: #5B9BD5; }"; // 蓝色表示曝光
    } else if (currentPhase == PHASE_READOUT) {
        style = "QProgressBar::chunk { background: #70AD47; }"; // 绿色表示读出
    }
    ui->ExposureprogressBar->setStyleSheet(style);
}


void MainWindow::handleStatusResponse(const QString &response)
{

    //camera_status:ID=z1$ready=-1$shutter=0$rate=1
    QStringList parts = response.mid(response.indexOf(':')+1).split('$');
    foreach (const QString &part, parts) {
        QStringList kv = part.split('=');
        if (kv.size() == 2) {
            if (kv[0] == "ID") {
                cameraState.id = kv[1];
            } else if (kv[0] == "ready") {
                cameraState.status = kv[1].toInt();
                updateMasterLedStatus(true); // 状态变化时立即更新指示灯
            } else if (kv[0] == "shutter") {
                cameraState.shutter = kv[1].toInt();
            } else if (kv[0] == "rate") {
                cameraState.rate = kv[1];
            }
        }
        if (kv[0] == "status") {
            cameraState.status = kv[1].toInt();
            updateMasterLedStatus(true); // 状态变化时立即更新指示灯
        }
    }

    // 更新UI显示
    QString statusText;
    switch (cameraState.status) {
    case -1: statusText = "未上电"; break;
    case 0: statusText = "空闲"; break;
    case 1: statusText = "曝光中"; break;
    case 2: statusText = "读出中"; break;
    }
    ui->labelCameraStatus->setText(QString("状态: %1 | 快门: %2 | 读出: %3")
                                       .arg(statusText)
                                       .arg(cameraState.shutter ? "开" : "关")
                                       .arg(cameraState.rate));
    // 根据新状态更新控件
    bool isExposing = (cameraState.status != 0);
    updateCameraControls(isExposing);

}

void MainWindow::sequenceFinished()
{
    // 1. 更新UI状态
    ui->btnStartSequence->setEnabled(true);
    ui->btnStopSequence->setEnabled(false);
    //ui->labelSequenceProgress->setText("序列拍摄已完成");
    ui->btnStartExposure->setEnabled(true); // added by XYH@20250527

    // 2. 重置序列相关变量
    currentSequenceIndex = -1;
    isSequenceRunning = false;
    sequenceTasks.clear();

    // 3. 记录日志
    if(m_sequenceAborted) {
        LOG_GENERAL("用户中断了拍摄序列");
        m_sequenceAborted = false;
    } else {
        LOG_GENERAL("所有拍摄序列任务已完成");
    }

    // 4. 可选: 播放完成音效或显示通知
    QApplication::beep();

    // 5. 恢复相机状态
    if(cameraState.status != 0) {
        sendCameraCommand("abort_290");
    }

    // 6. 更新状态显示
    updateCameraStatus();
}

void MainWindow::updateCameraStatus()
{
    QString statusText;
    QString statusColor;

    switch (hwStatus.cameraState) {
    case Idle:
        statusText = "IDLE";
        statusColor = "green";
        break;
    case Waiting:
        statusText = "WAITING";
        statusColor = "blue";
        break;
    case Exposing:
        statusText = "EXPOSING";
        statusColor = "orange";
        break;
    case Reading:
        statusText = "READING";
        statusColor = "purple";
        break;
    case Downloading:
        statusText = "DOWNLOADING";
        statusColor = "cyan";
        break;
    case Error:
        statusText = "ERROR";
        statusColor = "red";
        break;
    }
    // 更新主板卡指示灯状态
    //updateMasterLedStatus();

    //ui->lblCameraStatus_2->setText(statusText);
    //ui->lblCameraStatus_2->setStyleSheet(
    // QString("background-color: %1; color: white; padding: 5px; border-radius: 5px;")
    //.arg(statusColor));
}

